home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / filecmp.py < prev    next >
Encoding:
Python Source  |  2000-03-29  |  1.5 KB  |  69 lines

  1. """Compare files."""
  2.  
  3. import os, stat, statcache
  4.  
  5. _cache = {}
  6. BUFSIZE=8*1024
  7.  
  8. def cmp(f1, f2, shallow=1,use_statcache=0): 
  9.     """Compare two files.
  10.  
  11.     Arguments:
  12.  
  13.     f1 -- First file name
  14.  
  15.     f2 -- Second file name
  16.  
  17.     shallow -- Just check stat signature (do not read the files).
  18.                defaults to 1.
  19.  
  20.     use_statcache -- Do not stat() each file directly: go through
  21.                      the statcache module for more efficiency.
  22.  
  23.     Return value:
  24.  
  25.     integer -- 1 if the files are the same, 0 otherwise.
  26.  
  27.     This function uses a cache for past comparisons and the results,
  28.     with a cache invalidation mechanism relying on stale signatures.
  29.     Of course, if 'use_statcache' is true, this mechanism is defeated,
  30.     and the cache will never grow stale.
  31.  
  32.     """
  33.     if use_statcache:
  34.         stat_function = statcache.stat
  35.     else:
  36.         stat_function = os.stat
  37.     s1 = _sig(stat_function(f1))
  38.     s2 = _sig(stat_function(f2))
  39.     if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG:
  40.         return 0
  41.     if shallow and s1 == s2:
  42.         return 1
  43.     if s1[1] != s2[1]:
  44.         return 0
  45.  
  46.     result = _cache.get((f1, f2))
  47.     if result and (s1, s2) == result[:2]:
  48.         return result[2]
  49.     outcome = _do_cmp(f1, f2)
  50.     _cache[f1, f2] = s1, s2, outcome
  51.     return outcome
  52.  
  53. def _sig(st):
  54.     return (stat.S_IFMT(st[stat.ST_MODE]), 
  55.             st[stat.ST_SIZE], 
  56.             st[stat.ST_MTIME])
  57.  
  58. def _do_cmp(f1, f2):
  59.     bufsize = BUFSIZE
  60.     fp1 = open(f1, 'rb')
  61.     fp2 = open(f2, 'rb')
  62.     while 1:
  63.         b1 = fp1.read(bufsize)
  64.         b2 = fp2.read(bufsize)
  65.         if b1 != b2:
  66.             return 0
  67.         if not b1:
  68.             return 1
  69.